/**
 * @author phi
 */

(function(){ "use strict"; })();



/**
 * @namespace
 * @memberof    TM
 */
TM.Geom = TM.Geom || {};

(function(){
    
    /**
     * @lends   TM.Geom.Quaternion.prototype
     */
    TM.Geom.Quaternion = TM.createClass({
        x: 0,
        y: 0,
        
        /**
         * クォータニオン
         * @constructs
         * @see <a href="http://tmlib-js.googlecode.com/svn/trunk/test/geom/quaternion-test.html">Test Program</a>.
         */
        init: function(x, y, z, w) {
            this.set(x, y, z, w);
        },
        
        /**
         * セット
         */
        set: function(x, y, z, w) {
            this.x = x;
            this.y = y;
            this.z = z;
            this.w = w;
            
            return this;
        },
        
        setFromAxisAngle: function(axis, angle)
        {
            var deg = angle * Math.PI/180;
            var halfDeg = deg * 0.5;
            var halfSin = Math.sin(halfDeg);
            var halfCos = Math.cos(halfDeg);
            
            this.x = axis.x * halfSin;
            this.y = axis.y * halfSin;
            this.z = axis.z * halfSin;
            this.w = halfCos;
            
            return this;
        },
        
        identity: function() {
            this.x = 0;
            this.y = 0;
            this.z = 0;
            this.w = 1;
            
            return this;
        },
        
        toMatrix: function() {
            var m00, m01, m02;
            var m10, m11, m22;
            var m20, m21, m32;
            
            // 先に計算しておく
            var ww = 2.0 * this.w;
            var xx = 2.0 * this.x;
            var yy = 2.0 * this.y;
            var zz = 2.0 * this.z;
            
            // 行列の要素を設定
            // X軸
            m00 = 1.0 - yy*this.y - zz*this.z;
            m10 = xx*this.y + ww*this.z;
            m20 = xx*this.z - ww*this.y;
            // Y軸
            m01 = xx*this.y - ww*this.z;
            m11 = 1.0 - xx*this.x - zz*this.z;
            m21 = yy*this.z + ww*this.x;
            // Z軸
            m02 = xx*this.z + ww*this.y;
            m12 = yy*this.z - ww*this.x;
            m22 = 1.0 - xx*this.x - yy*this.y;
            
            return TM.$M44(
                m00, m01, m02, 0.0,
                m10, m11, m12, 0.0,
                m20, m21, m22, 0.0,
                0.0, 0.0, 0.0, 1.0
            );
        },
        
    });
    
    
    /**
     * ゼロベクトル
     */
    // TM.Geom.Quaternion.ZERO    = TM.Geom.Quaternion( 0, 0);
    
    console.assert(!TM.$Quat, "名前が競合しています!!", "$Quat");
    /**
     * TM.Math.Vector2 の alias.
     * short hand としてお使いください.
     */
    TM.$Quat = TM.Geom.Quaternion;
    
})();

